package com.gray.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gray.cache.JedisUtil;
import com.gray.dao.SectionDao;
import com.gray.pojo.Section;
import com.gray.service.ISectionService;

@Service
public class SectionServiceImpl implements ISectionService {

	@Autowired
	private SectionDao sectionDao;
	
	@Autowired
	private JedisUtil.Keys jedisKeys;
	
	@Autowired
	private JedisUtil.Strings jedisStrings;
	
	private static String SECTIONKEYS = "sectionlist";
	
	
	@Override
	@Transactional
	public List<Section> getAllSection() {
		String key = SECTIONKEYS;
		List<Section> sectionList = null;
		ObjectMapper mapper = new ObjectMapper();
		if(!jedisKeys.exists(key)){
			sectionList = sectionDao.selectAllSection();
			System.out.println("jedisKeys 不存在");
			try {
				String jsonString = mapper.writeValueAsString(sectionList);
				jedisStrings.set(key, jsonString);
			} catch (JsonGenerationException e) {
				e.printStackTrace();
				throw new RuntimeException();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			String jsonString = jedisStrings.get(key);
			JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, Section.class);
			System.out.println("jedisKeys 存在");
			try {
				sectionList = mapper.readValue(jsonString, javaType);
			} catch (JsonParseException e) {
				e.printStackTrace();
				throw new RuntimeException();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException();
			}
		}
		return sectionList;
	}


	@Override
	public Map getSection(int currentPage, int pageSize) {
		// TODO Auto-generated method stub
		PageHelper.startPage(currentPage, pageSize);
		List<Section> list = sectionDao.selectAllSection();
		PageInfo<Section> pageInfo = new PageInfo<Section>(list);
		Map map = new HashMap();
		map.put("section", list);
		map.put("pageInfo", pageInfo);
		return map;
	}

}
